package com.pengtu.gsj.service.impl.dl;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pengtu.gsj.dao.base.Page;
import com.pengtu.gsj.dao.base.QueryFilter;
import com.pengtu.gsj.dao.dl.TunnelInfoDao;
import com.pengtu.gsj.entity.dl.TunnelInfo;
import com.pengtu.gsj.service.dl.TunnelinfoService;
import com.pengtu.gsj.utils.ConfigUtils;
import com.pengtu.gsj.utils.encode.JsonBinder;

/**
 * 
 * 
 * TunnelinfoServiceImpl
 * 
 * 2017年4月19日 下午4:33:10
 * 
 * @version 1.0.0
 * 
 */
@Transactional
@Service
public class TunnelinfoServiceImpl implements TunnelinfoService {

	@Autowired
	private TunnelInfoDao tunnelinfoDao;

	@Override
	public List<TunnelInfo> getTunnelinfos(QueryFilter queryFilter) {
		return tunnelinfoDao.find(queryFilter);
	}

	@Override
	public Page<TunnelInfo> findTunnelinfos(Page<TunnelInfo> page,
			QueryFilter queryFilter) {
		return tunnelinfoDao.findPage(page, queryFilter);
	}

	@Override
	public TunnelInfo getTunnelinfo(String id) {
		return tunnelinfoDao.get(id);
	}

	@Override
	public void saveTunnelinfo(TunnelInfo tunnelinfo) {
		tunnelinfoDao.save(tunnelinfo);
	}

	@Override
	public void deleteTunnelinfo(String id) {
		tunnelinfoDao.delete(id);

	}

	@Override
	public void dockingTunnelInfo() throws Exception {
		String urlString = ConfigUtils.getConfig("ssjcAddress");
		// 如果从文件中读取的URL地址最后一个字符不是 '\'，则添加'\'    
        if (urlString.charAt(urlString.length() - 1) != '/') {    
        	urlString += "/";    
        } 
        urlString+="dl/tunnelinfo!dockingAllTunnel.action";
        URL url;
		StringBuffer st=new StringBuffer();
		url = new URL(urlString);
		URLConnection urlData=url.openConnection();
		urlData.setConnectTimeout(30000);
		BufferedReader reader =new BufferedReader(new InputStreamReader(urlData.getInputStream(),"utf-8"));
		String line=null;
		while((line=reader.readLine())!=null){
			st.append(line);
		}
		JsonBinder jsonBinder = new JsonBinder(Inclusion.ALWAYS);
		List<TunnelInfo> list = jsonBinder.fromJsonList(st.toString(), new TypeReference<List<TunnelInfo>>() {});
		if (list != null) {
			for (TunnelInfo tunnelInfo : list) {
				tunnelinfoDao.save(tunnelInfo);
			}
		}	
	}
	public List<TunnelInfo> getAllTunnelInfo() {
		return tunnelinfoDao.getAll();
	}

}
